using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Resources;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

using XPTable;
using XPTable.Editors;
using XPTable.Models;

using System.Reflection;
using PinkieControls;
using Model;


namespace View
{
	/// <summary>
	/// Summary description for TransactionView.
	/// </summary>
	public class TransactionView : System.Windows.Forms.Form
	{

		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label typeLabel;
		private System.Windows.Forms.ComboBox typeComboBox;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ComboBox accountComboBox;
		private XPTable.Models.Table payeesTable;
		private XPTable.Models.Table consumersTable;
		private PinkieControls.ButtonXP addButton;
		private PinkieControls.ButtonXP cancelButton;
		private System.Windows.Forms.Label dateLabel;
		private System.Windows.Forms.DateTimePicker dateTimePicker1;
		private PinkieControls.ButtonXP addPayeeButton;
		private PinkieControls.ButtonXP remPayeeButton;
		private PinkieControls.ButtonXP addConsumerButton;
		private PinkieControls.ButtonXP remConsumerButton;

		static ResourceManager rm;
		private System.Windows.Forms.GroupBox totalAmountgroupBox;
        private System.Windows.Forms.Label totalAmountLabel;
		private System.Windows.Forms.TextBox descriptionBox;

		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		private Model.UserManager manager;
		private System.Windows.Forms.TextBox subjectField;
		private PinkieControls.ButtonXP updateButton;
		private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.TextBox amountBox;
		private System.Windows.Forms.Label amountLabel;
		private Model.Transaction transaction = null;

		public TransactionView(Model.UserManager mymanager)
		{
			manager = mymanager;
            // handle the situation where the server gets disconnected
            this.manager.ServiceDisconnectedAction += new Model.UserManager.ServiceDisconnectedEventHandler(onServerDisconnected);
			
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			accountComboBox.Items.AddRange(manager.GetExternalAccountList());
			accountComboBox.SelectedIndex = 0;
			typeComboBox.SelectedIndex = 0;
			updateButton.Visible = false;
			amountLabel.Visible = false;
			amountBox.Visible = false;
		}

		public TransactionView(Model.UserManager mymanager, Model.Transaction tx)
		{
			
			manager = mymanager;
			transaction = tx;

            // handle the situation where the server gets disconnected
            this.manager.ServiceDisconnectedAction += new Model.UserManager.ServiceDisconnectedEventHandler(onServerDisconnected);
			
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			addButton.Visible = false;
			dateTimePicker1.Enabled = false;
			typeComboBox.Enabled = false;
			accountComboBox.Items.AddRange(manager.GetExternalAccountList());
			displayInfo();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			
			//payeesTable build
			this.payeesTable.BeginUpdate();

			ComboBoxColumn payeeNameColumn = new ComboBoxColumn();
			payeeNameColumn.Text = "Name";
			payeeNameColumn.Editable = true;
			payeeNameColumn.ToolTipText = "Payee's name for a shared transaction";
			payeeNameColumn.Width = 140;

			ComboBoxCellEditor genreEditor = new ComboBoxCellEditor();
			genreEditor.DropDownStyle = DropDownStyle.DropDownList;
			genreEditor.Items.AddRange(manager.GetAllUserNames());
			//genreEditor.Items.AddRange(new string[]{"Jack"});
			payeeNameColumn.Editor = genreEditor;

			TextColumn amountColumn = new TextColumn();
			//amountColumn.Maximum = 1000000;
			amountColumn.Editable = true;
			amountColumn.Text = "Amount $";
			amountColumn.ToolTipText = "The amount involved in this transaction";
			amountColumn.Width = 76;

			this.payeesTable.ColumnModel = new ColumnModel(new Column[] {
																			payeeNameColumn,
																			amountColumn

																		});

			this.payeesTable.TableModel = new TableModel(new Row[] {	
																			

																   });

			this.payeesTable.HeaderRenderer = new XPTable.Renderers.GradientHeaderRenderer();
			this.payeesTable.TableModel.RowHeight += 3;
			this.payeesTable.FullRowSelect = true;

			this.payeesTable.EndUpdate();

			//Consumer table update

			this.consumersTable.BeginUpdate();

			ComboBoxColumn consumerNameColumn = new ComboBoxColumn();
			consumerNameColumn.Text = "Name";
			consumerNameColumn.Editable = true;
			consumerNameColumn.ToolTipText = "Payee's name for a shared transaction";
			consumerNameColumn.Width = 140;

			ComboBoxCellEditor genreEditor2 = new ComboBoxCellEditor();
			genreEditor2.DropDownStyle = DropDownStyle.DropDownList;
			genreEditor2.Items.AddRange(manager.GetAllUserNames());
				//genreEditor2.Items.AddRange(new string[]{"Jack"});
			consumerNameColumn.Editor = genreEditor2;

			TextColumn amountColumn2 = new TextColumn();
			//amountColumn2.Maximum = 1000000;
			amountColumn2.Editable = true;
			amountColumn2.Text = "Amount $";
			amountColumn2.ToolTipText = "The amount involved in this transaction";
			amountColumn2.Width = 76;

			this.consumersTable.ColumnModel = new ColumnModel(new Column[] {
																			   consumerNameColumn,
																			   amountColumn2

																		   });

			this.consumersTable.TableModel = new TableModel(new Row[] {	
																			

																	  });

			this.consumersTable.HeaderRenderer = new XPTable.Renderers.GradientHeaderRenderer();
			this.consumersTable.TableModel.RowHeight += 3;
			this.consumersTable.FullRowSelect = true;

			this.consumersTable.EndUpdate();

			

			if(transaction!=null)
				refreshTables();
			else //add default row
			{
				payeesTable.TableModel.Rows.Insert(0, new Row(new Cell[] {
																			 new Cell(manager.CurrentUserID.Name),
																			 new Cell("0.0")
																		 }));
				consumersTable.TableModel.Rows.Insert(0, new Row(new Cell[] {
																				new Cell(manager.CurrentUserID.Name),
																				new Cell("0.0")
																			}));
			}


		}


		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.label1 = new System.Windows.Forms.Label();
            this.subjectField = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.descriptionBox = new System.Windows.Forms.TextBox();
            this.typeLabel = new System.Windows.Forms.Label();
            this.typeComboBox = new System.Windows.Forms.ComboBox();
            this.label3 = new System.Windows.Forms.Label();
            this.accountComboBox = new System.Windows.Forms.ComboBox();
            this.payeesTable = new XPTable.Models.Table();
            this.consumersTable = new XPTable.Models.Table();
            this.addButton = new PinkieControls.ButtonXP();
            this.cancelButton = new PinkieControls.ButtonXP();
            this.dateLabel = new System.Windows.Forms.Label();
            this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
            this.addPayeeButton = new PinkieControls.ButtonXP();
            this.remPayeeButton = new PinkieControls.ButtonXP();
            this.addConsumerButton = new PinkieControls.ButtonXP();
            this.remConsumerButton = new PinkieControls.ButtonXP();
            this.totalAmountgroupBox = new System.Windows.Forms.GroupBox();
            this.totalAmountLabel = new System.Windows.Forms.Label();
            this.updateButton = new PinkieControls.ButtonXP();
            this.toolBar1 = new System.Windows.Forms.ToolBar();
            this.amountLabel = new System.Windows.Forms.Label();
            this.amountBox = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.payeesTable)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.consumersTable)).BeginInit();
            this.totalAmountgroupBox.SuspendLayout();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(16, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(48, 16);
            this.label1.TabIndex = 0;
            this.label1.Text = "Subject:";
            // 
            // subjectField
            // 
            this.subjectField.Location = new System.Drawing.Point(16, 32);
            this.subjectField.Name = "subjectField";
            this.subjectField.Size = new System.Drawing.Size(304, 20);
            this.subjectField.TabIndex = 1;
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(16, 64);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 16);
            this.label2.TabIndex = 2;
            this.label2.Text = "Description:";
            // 
            // descriptionBox
            // 
            this.descriptionBox.Location = new System.Drawing.Point(16, 80);
            this.descriptionBox.Multiline = true;
            this.descriptionBox.Name = "descriptionBox";
            this.descriptionBox.Size = new System.Drawing.Size(304, 117);
            this.descriptionBox.TabIndex = 3;
            // 
            // typeLabel
            // 
            this.typeLabel.Location = new System.Drawing.Point(336, 112);
            this.typeLabel.Name = "typeLabel";
            this.typeLabel.Size = new System.Drawing.Size(40, 16);
            this.typeLabel.TabIndex = 4;
            this.typeLabel.Text = "Type:";
            // 
            // typeComboBox
            // 
            this.typeComboBox.Items.AddRange(new object[] {
            "Expense",
            "Revenue",
            "Transfer between users",
            "Transfer between accounts"});
            this.typeComboBox.Location = new System.Drawing.Point(336, 128);
            this.typeComboBox.Name = "typeComboBox";
            this.typeComboBox.Size = new System.Drawing.Size(136, 21);
            this.typeComboBox.TabIndex = 5;
            this.typeComboBox.SelectedIndexChanged += new System.EventHandler(this.typeComboBox_SelectedIndexChanged);
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(336, 64);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(48, 16);
            this.label3.TabIndex = 6;
            this.label3.Text = "Account:";
            // 
            // accountComboBox
            // 
            this.accountComboBox.Location = new System.Drawing.Point(336, 80);
            this.accountComboBox.Name = "accountComboBox";
            this.accountComboBox.Size = new System.Drawing.Size(136, 21);
            this.accountComboBox.TabIndex = 7;
            // 
            // payeesTable
            // 
            this.payeesTable.AlternatingRowColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(237)))), ((int)(((byte)(245)))));
            this.payeesTable.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.payeesTable.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(237)))), ((int)(((byte)(242)))), ((int)(((byte)(249)))));
            this.payeesTable.EditStartAction = XPTable.Editors.EditStartAction.SingleClick;
            this.payeesTable.EnableToolTips = true;
            this.payeesTable.Font = new System.Drawing.Font("Tahoma", 8.25F);
            this.payeesTable.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
            this.payeesTable.GridColor = System.Drawing.SystemColors.ControlDark;
            this.payeesTable.GridLines = XPTable.Models.GridLines.Both;
            this.payeesTable.GridLineStyle = XPTable.Models.GridLineStyle.Dot;
            this.payeesTable.HeaderFont = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
            this.payeesTable.Location = new System.Drawing.Point(16, 216);
            this.payeesTable.MultiSelect = true;
            this.payeesTable.Name = "payeesTable";
            this.payeesTable.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(169)))), ((int)(((byte)(183)))), ((int)(((byte)(201)))));
            this.payeesTable.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
            this.payeesTable.SelectionStyle = XPTable.Models.SelectionStyle.Grid;
            this.payeesTable.Size = new System.Drawing.Size(224, 152);
            this.payeesTable.SortedColumnBackColor = System.Drawing.Color.Transparent;
            this.payeesTable.TabIndex = 8;
            this.payeesTable.UnfocusedSelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(201)))), ((int)(((byte)(210)))), ((int)(((byte)(221)))));
            this.payeesTable.UnfocusedSelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
            this.payeesTable.KeyUp += new System.Windows.Forms.KeyEventHandler(this.payeesTable_KeyUp);
            this.payeesTable.CellPropertyChanged += new XPTable.Events.CellEventHandler(this.payeesTable_CellPropertyChanged);
            // 
            // consumersTable
            // 
            this.consumersTable.AlternatingRowColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(237)))), ((int)(((byte)(245)))));
            this.consumersTable.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.consumersTable.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(237)))), ((int)(((byte)(242)))), ((int)(((byte)(249)))));
            this.consumersTable.EnableToolTips = true;
            this.consumersTable.Font = new System.Drawing.Font("Tahoma", 8.25F);
            this.consumersTable.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
            this.consumersTable.GridColor = System.Drawing.SystemColors.ControlDark;
            this.consumersTable.GridLines = XPTable.Models.GridLines.Both;
            this.consumersTable.GridLineStyle = XPTable.Models.GridLineStyle.Dot;
            this.consumersTable.HeaderFont = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
            this.consumersTable.Location = new System.Drawing.Point(248, 216);
            this.consumersTable.MultiSelect = true;
            this.consumersTable.Name = "consumersTable";
            this.consumersTable.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(169)))), ((int)(((byte)(183)))), ((int)(((byte)(201)))));
            this.consumersTable.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
            this.consumersTable.SelectionStyle = XPTable.Models.SelectionStyle.Grid;
            this.consumersTable.Size = new System.Drawing.Size(224, 152);
            this.consumersTable.SortedColumnBackColor = System.Drawing.Color.Transparent;
            this.consumersTable.TabIndex = 11;
            this.consumersTable.UnfocusedSelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(201)))), ((int)(((byte)(210)))), ((int)(((byte)(221)))));
            this.consumersTable.UnfocusedSelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(14)))), ((int)(((byte)(66)))), ((int)(((byte)(121)))));
            this.consumersTable.CellPropertyChanged += new XPTable.Events.CellEventHandler(this.consumersTable_CellPropertyChanged);
            // 
            // addButton
            // 
            this.addButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))));
            this.addButton.DefaultScheme = true;
            this.addButton.DialogResult = System.Windows.Forms.DialogResult.None;
            this.addButton.Hint = "";
            this.addButton.Location = new System.Drawing.Point(16, 496);
            this.addButton.Name = "addButton";
            this.addButton.Scheme = PinkieControls.ButtonXP.Schemes.Silver;
            this.addButton.Size = new System.Drawing.Size(104, 24);
            this.addButton.TabIndex = 17;
            this.addButton.Text = "Add";
            this.addButton.Click += new System.EventHandler(this.addButton_Click);
            // 
            // cancelButton
            // 
            this.cancelButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))));
            this.cancelButton.DefaultScheme = true;
            this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.None;
            this.cancelButton.Hint = "";
            this.cancelButton.Location = new System.Drawing.Point(120, 496);
            this.cancelButton.Name = "cancelButton";
            this.cancelButton.Scheme = PinkieControls.ButtonXP.Schemes.Silver;
            this.cancelButton.Size = new System.Drawing.Size(104, 24);
            this.cancelButton.TabIndex = 18;
            this.cancelButton.Text = "Cancel";
            this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
            // 
            // dateLabel
            // 
            this.dateLabel.Location = new System.Drawing.Point(336, 16);
            this.dateLabel.Name = "dateLabel";
            this.dateLabel.Size = new System.Drawing.Size(32, 16);
            this.dateLabel.TabIndex = 19;
            this.dateLabel.Text = "Date:";
            // 
            // dateTimePicker1
            // 
            this.dateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Short;
            this.dateTimePicker1.Location = new System.Drawing.Point(336, 32);
            this.dateTimePicker1.Name = "dateTimePicker1";
            this.dateTimePicker1.Size = new System.Drawing.Size(136, 20);
            this.dateTimePicker1.TabIndex = 20;
            // 
            // addPayeeButton
            // 
            this.addPayeeButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))));
            this.addPayeeButton.DefaultScheme = true;
            this.addPayeeButton.DialogResult = System.Windows.Forms.DialogResult.None;
            this.addPayeeButton.Hint = "";
            this.addPayeeButton.Location = new System.Drawing.Point(16, 376);
            this.addPayeeButton.Name = "addPayeeButton";
            this.addPayeeButton.Scheme = PinkieControls.ButtonXP.Schemes.Silver;
            this.addPayeeButton.Size = new System.Drawing.Size(104, 24);
            this.addPayeeButton.TabIndex = 21;
            this.addPayeeButton.Text = "Add Payee";
            this.addPayeeButton.Click += new System.EventHandler(this.addPayeeButton_Click);
            // 
            // remPayeeButton
            // 
            this.remPayeeButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))));
            this.remPayeeButton.DefaultScheme = true;
            this.remPayeeButton.DialogResult = System.Windows.Forms.DialogResult.None;
            this.remPayeeButton.Hint = "";
            this.remPayeeButton.Location = new System.Drawing.Point(120, 376);
            this.remPayeeButton.Name = "remPayeeButton";
            this.remPayeeButton.Scheme = PinkieControls.ButtonXP.Schemes.Silver;
            this.remPayeeButton.Size = new System.Drawing.Size(104, 24);
            this.remPayeeButton.TabIndex = 22;
            this.remPayeeButton.Text = "Remove Payee";
            this.remPayeeButton.Click += new System.EventHandler(this.remPayeeButton_Click);
            // 
            // addConsumerButton
            // 
            this.addConsumerButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))));
            this.addConsumerButton.DefaultScheme = true;
            this.addConsumerButton.DialogResult = System.Windows.Forms.DialogResult.None;
            this.addConsumerButton.Hint = "";
            this.addConsumerButton.Location = new System.Drawing.Point(248, 376);
            this.addConsumerButton.Name = "addConsumerButton";
            this.addConsumerButton.Scheme = PinkieControls.ButtonXP.Schemes.Silver;
            this.addConsumerButton.Size = new System.Drawing.Size(104, 24);
            this.addConsumerButton.TabIndex = 23;
            this.addConsumerButton.Text = "Add Consumer";
            this.addConsumerButton.Click += new System.EventHandler(this.addConsumerButton_Click);
            // 
            // remConsumerButton
            // 
            this.remConsumerButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))));
            this.remConsumerButton.DefaultScheme = true;
            this.remConsumerButton.DialogResult = System.Windows.Forms.DialogResult.None;
            this.remConsumerButton.Hint = "";
            this.remConsumerButton.Location = new System.Drawing.Point(352, 376);
            this.remConsumerButton.Name = "remConsumerButton";
            this.remConsumerButton.Scheme = PinkieControls.ButtonXP.Schemes.Silver;
            this.remConsumerButton.Size = new System.Drawing.Size(104, 24);
            this.remConsumerButton.TabIndex = 24;
            this.remConsumerButton.Text = "Remove Consumer";
            this.remConsumerButton.Click += new System.EventHandler(this.remConsumerButton_Click);
            // 
            // totalAmountgroupBox
            // 
            this.totalAmountgroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.totalAmountgroupBox.Controls.Add(this.totalAmountLabel);
            this.totalAmountgroupBox.Location = new System.Drawing.Point(16, 416);
            this.totalAmountgroupBox.Name = "totalAmountgroupBox";
            this.totalAmountgroupBox.Size = new System.Drawing.Size(456, 64);
            this.totalAmountgroupBox.TabIndex = 25;
            this.totalAmountgroupBox.TabStop = false;
            this.totalAmountgroupBox.Text = "Total amount";
            // 
            // totalAmountLabel
            // 
            this.totalAmountLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.totalAmountLabel.Location = new System.Drawing.Point(6, 16);
            this.totalAmountLabel.Name = "totalAmountLabel";
            this.totalAmountLabel.Size = new System.Drawing.Size(444, 45);
            this.totalAmountLabel.TabIndex = 0;
            this.totalAmountLabel.Text = "0.00";
            // 
            // updateButton
            // 
            this.updateButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))), ((int)(((byte)(220)))));
            this.updateButton.DefaultScheme = true;
            this.updateButton.DialogResult = System.Windows.Forms.DialogResult.None;
            this.updateButton.Hint = "";
            this.updateButton.Location = new System.Drawing.Point(16, 496);
            this.updateButton.Name = "updateButton";
            this.updateButton.Scheme = PinkieControls.ButtonXP.Schemes.Silver;
            this.updateButton.Size = new System.Drawing.Size(104, 24);
            this.updateButton.TabIndex = 26;
            this.updateButton.Text = "Update";
            this.updateButton.Click += new System.EventHandler(this.updateButton_Click);
            // 
            // toolBar1
            // 
            this.toolBar1.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.toolBar1.DropDownArrows = true;
            this.toolBar1.Location = new System.Drawing.Point(0, 486);
            this.toolBar1.Name = "toolBar1";
            this.toolBar1.ShowToolTips = true;
            this.toolBar1.Size = new System.Drawing.Size(490, 42);
            this.toolBar1.TabIndex = 27;
            // 
            // amountLabel
            // 
            this.amountLabel.Location = new System.Drawing.Point(336, 160);
            this.amountLabel.Name = "amountLabel";
            this.amountLabel.Size = new System.Drawing.Size(48, 16);
            this.amountLabel.TabIndex = 28;
            this.amountLabel.Text = "Amount:";
            // 
            // amountBox
            // 
            this.amountBox.Location = new System.Drawing.Point(336, 176);
            this.amountBox.Name = "amountBox";
            this.amountBox.Size = new System.Drawing.Size(136, 20);
            this.amountBox.TabIndex = 29;
            this.amountBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.amountBox_KeyUp);
            this.amountBox.TextChanged += new System.EventHandler(this.amountBox_TextChanged);
            // 
            // TransactionView
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.BackColor = System.Drawing.Color.Gainsboro;
            this.ClientSize = new System.Drawing.Size(490, 528);
            this.Controls.Add(this.amountBox);
            this.Controls.Add(this.amountLabel);
            this.Controls.Add(this.cancelButton);
            this.Controls.Add(this.addButton);
            this.Controls.Add(this.updateButton);
            this.Controls.Add(this.toolBar1);
            this.Controls.Add(this.remConsumerButton);
            this.Controls.Add(this.addConsumerButton);
            this.Controls.Add(this.remPayeeButton);
            this.Controls.Add(this.addPayeeButton);
            this.Controls.Add(this.consumersTable);
            this.Controls.Add(this.payeesTable);
            this.Controls.Add(this.descriptionBox);
            this.Controls.Add(this.subjectField);
            this.Controls.Add(this.totalAmountgroupBox);
            this.Controls.Add(this.dateTimePicker1);
            this.Controls.Add(this.dateLabel);
            this.Controls.Add(this.accountComboBox);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.typeComboBox);
            this.Controls.Add(this.typeLabel);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Name = "TransactionView";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Add new transaction";
            ((System.ComponentModel.ISupportInitialize)(this.payeesTable)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.consumersTable)).EndInit();
            this.totalAmountgroupBox.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		private void displayInfo()
		{
			subjectField.Text = transaction.Subject;
			descriptionBox.Text = transaction.CategoryDescription;
			dateTimePicker1.Value = transaction.Date;
			typeComboBox.Text = transaction.Type;
			accountComboBox.Text = transaction.SourceExternalAccount;
            totalAmountLabel.Text = transaction.getTotalAmount() + interpretTransactionResult() ;   //TODO: remove and add an update function
			amountBox.Text = transaction.getTotalAmount().ToString();
			
			//refreshTables();
		}

		private void refreshTables()
		{
			UserAmountPair user;

			ArrayList iniPayees = new ArrayList();
			ArrayList iniConsumers = new ArrayList();

			iniPayees = transaction.InvolvedPayees;
			iniConsumers = transaction.InvolvedConsumers;


			for(int i = 0; i<iniPayees.Count; i++)
			{
				user = (UserAmountPair)iniPayees[i];

				payeesTable.TableModel.Rows.Insert(i, new Row(new Cell[] {
																						new Cell(user.username),
																						new Cell(user.amount.ToString())
																					}));

			}
	
			for(int i = 0; i<iniConsumers.Count; i++)
			{
				user = (UserAmountPair)iniConsumers[i];
				consumersTable.TableModel.Rows.Insert(i, new Row(new Cell[] {
																						   new Cell(user.username),
																						   new Cell(user.amount.ToString())
																	   }));
			}
		}


		private void addPayeeButton_Click(object sender, System.EventArgs e)
		{
			int totalRow = payeesTable.TableModel.Rows.Count;
			payeesTable.TableModel.Rows.Insert((totalRow+1), new Row(new Cell[] {
																					new Cell(""),
																					new Cell("0.0")
																				}));
		}

		private void cancelButton_Click(object sender, System.EventArgs e)
		{
			this.Dispose();
		}

		private void remPayeeButton_Click(object sender, System.EventArgs e)
		{
			int[] selectedPayee = payeesTable.SelectedIndicies;
			payeesTable.TableModel.Rows.RemoveAt(selectedPayee[0]);
			
			// Update total amount displayed
            showTotalAmount();

		}

        /*
        /// <summary>
        /// Updates the result text with a summary of the transaction.
        /// </summary>
        private void updateResult()
        {
            // Update total amount displayed
			double amount = 0;
			for (int i = 0; i < payeesTable.TableModel.Rows.Count; i++)
			{
				amount += Convert.ToDouble(payeesTable.TableModel.Rows[i].Cells[1].Text);
			}
			totalAmountLabel.Text = amount.ToString();
            
            if (transaction == null) return;    // if it is a new transaction

            if (transaction.isShared())
            {

                totalAmountLabel.Text = amount.ToString() + "$ to be divided so that: " + interpretTransactionResult();
            }
            else
            {
                totalAmountLabel.Text = amount.ToString() + "$";
            }
        }*/

		private void remConsumerButton_Click(object sender, System.EventArgs e)
		{
			int[] selectedConsumer = consumersTable.SelectedIndicies;
			consumersTable.TableModel.Rows.RemoveAt(selectedConsumer[0]);
		}

		private void addConsumerButton_Click(object sender, System.EventArgs e)
		{

			int totalRow = consumersTable.TableModel.Rows.Count;
			consumersTable.TableModel.Rows.Insert((totalRow+1), new Row(new Cell[] {
																					new Cell(""),
																					new Cell("0.0")
																 				}));
		}

		private void addButton_Click(object sender, System.EventArgs e)
		{
			addTransaction(false);
		}

		private void payeesTable_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			// If enter is pressed
			if (e.KeyCode == Keys.Enter)
			{
				showTotalAmount();
				
			}
		}

		private void showTotalAmount()
		{
            double amount = 0;
            for (int i = 0; i < payeesTable.TableModel.Rows.Count; i++)
            {

                if (checkCellValue(payeesTable.TableModel.Rows[i].Cells[1].Text))
                    amount += Convert.ToDouble(payeesTable.TableModel.Rows[i].Cells[1].Text);
                else
                    payeesTable.TableModel.Rows[i].Cells[1].Text = "0.0";

            }
            totalAmountLabel.Text = amount.ToString() + interpretTransactionResult();

		}

		private void updateButton_Click(object sender, System.EventArgs e)
		{
			addTransaction(true);
		}

        /// <summary>
        /// Find the result of a transaction interpreted as a string.
        /// If the transaction is not shared, returns empty string.
        /// </summary>
        /// <returns>List of strings of the form: x owns y$ from z. Returns "" if not shared. </returns>
        private string interpretTransactionResult()
        {
            if (transaction == null) return ""; //TODO: transaction result should follow from the form, not the transaction
            string result=". "; 
            if (transaction.isShared())
            {
                ArrayList txSummary = transaction.generateSummaryReport();
                foreach (ReportSharedTransaction iShare in txSummary)
                {
                    result += iShare.ToString() + " ";
                }
            }
            return result;
        }


		private void addTransaction(bool isUpdate)
		{
				// Error checking whether total paid amount equals consumed amount

				double amountPaid = 0;
				double amountConsumed = 0;
			
				for (int i = 0; i < payeesTable.TableModel.Rows.Count; i++)
				{
					amountPaid += Convert.ToDouble(payeesTable.TableModel.Rows[i].Cells[1].Text);
				}

				for (int i = 0; i < consumersTable.TableModel.Rows.Count; i++)
				{
					amountConsumed += Convert.ToDouble(consumersTable.TableModel.Rows[i].Cells[1].Text);
				}

				// if total amounts entered balance then create transaction object
				if (amountPaid == amountConsumed)
				{

					UserAmountPair user;
					int i, numberOfUsers;
					ArrayList iniPayees = new ArrayList();
					ArrayList iniConsumers = new ArrayList();
			
					user.username = "";
					user.amount = 0.0m;
			
					numberOfUsers = payeesTable.TableModel.Rows.Count;

					for(i = 0; i<numberOfUsers; i++)
					{
						user.username = payeesTable.TableModel.Rows[i].Cells[0].Text;
						user.amount = Convert.ToDecimal(payeesTable.TableModel.Rows[i].Cells[1].Text);
						iniPayees.Add(user);
					}
			
					numberOfUsers = consumersTable.TableModel.Rows.Count;
			
					for(i = 0; i<numberOfUsers; i++)
					{
						user.username = consumersTable.TableModel.Rows[i].Cells[0].Text;
						user.amount = Convert.ToDecimal(consumersTable.TableModel.Rows[i].Cells[1].Text);
						iniConsumers.Add(user);

					}
			
					string iniDate = dateTimePicker1.Text;
					string iniType = typeComboBox.Text;
					string iniCreator = manager.CurrentUserID.Name;
					//string iniTotalAmount = totalAmountLabel.Text;
		
					string iniSourceExternalAccount = accountComboBox.Text;
				
					string iniSubject = subjectField.Text;
					string iniCategoryDescrip = descriptionBox.Text;
					string iniDestExternalAccount = "";

					Model.Transaction newTransaction = new Model.Transaction(iniDate, iniType,iniCreator,
						iniConsumers,iniPayees,iniSourceExternalAccount,iniDestExternalAccount, iniSubject, iniCategoryDescrip);

					try
					{
					
						if(subjectField.TextLength == 0)	// was subject empty
						{//ask for confirmation
							DialogResult dlgRes = '\0';						
							dlgRes = MessageBox.Show(
								"Are you sure you want to create the transaction without writting a subject?", 
								"Confirm blank subject", 
								MessageBoxButtons.YesNo, 
								MessageBoxIcon.Question);

							if(!dlgRes.Equals(DialogResult.Yes)) // if no
							{ // return without adding
								return;
							} 
						}
						if(accountComboBox.SelectedIndex == -1)	// was subject empty
						{//ask for confirmation
							DialogResult dlgRes = '\0';						
							dlgRes = MessageBox.Show(
								"Please select the account you used to complete the transaction.", 
								"Account not specified", 
								MessageBoxButtons.OK, 
								MessageBoxIcon.Asterisk);

							if(dlgRes.Equals(DialogResult.OK)) // if ok
							{ // return without adding
								return;
							} 
						}

						if (isUpdate)	// if the function was called in update mode
						{
							manager.ModifyTransaction(transaction,newTransaction);
						}
						else
						{
							manager.AddTransaction(newTransaction); //TODO
						}
#if (DEBUG)
						MessageBox.Show("The transaction was successfully created.","Adding new transaction",MessageBoxButtons.OK,MessageBoxIcon.Information);
#endif
						this.Dispose();

					
					
					}
					catch(Exception exp)
					{
						MessageBox.Show("Could not add transaction.");
						MessageBox.Show(exp.Message);
					}

				
				}
					// if paid and consumed amounts dont balance
				else
				{
					MessageBox.Show("The total paid amount does not match the total consumed amount. Cannot record entry");
				}
				//payeesTable.Dispose();
				//consumersTable.Dispose();
			
		}

		private void payeesTable_CellPropertyChanged(object sender, XPTable.Events.CellEventArgs e)
		{
			showTotalAmount();
		}

		private bool checkCellValue(string amount)
		{
			double test;

			try
			{
				test = Convert.ToDouble(amount);
				return true;

			}
			catch
			{
				MessageBox.Show("bad input");
				return false;
			}

			
		}

		private void consumersTable_CellPropertyChanged(object sender, XPTable.Events.CellEventArgs e)
		{
			for (int i = 0; i < consumersTable.TableModel.Rows.Count; i++)
			{
				if(!checkCellValue(consumersTable.TableModel.Rows[i].Cells[1].Text))
					consumersTable.TableModel.Rows[i].Cells[1].Text = "0.0";

			}
		}

		private void typeComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if(typeComboBox.SelectedIndex==1)
			{
				amountLabel.Visible = true;
				amountBox.Visible = true;
				payeesTable.Enabled = false;
				consumersTable.Enabled = false;
				addConsumerButton.Enabled = false;
				remConsumerButton.Enabled = false;
				addPayeeButton.Enabled = false;
				remPayeeButton.Enabled = false;
			}
			else if(typeComboBox.SelectedIndex==0)
			{
				amountLabel.Visible = false;
				amountBox.Visible = false;
				
				payeesTable.Enabled = true;
				consumersTable.Enabled = true;
//				int totalRow = payeesTable.TableModel.Rows.Count;
//				while(totalRow!=1)
//				payeesTable.TableModel.Rows.RemoveAt(totalRow--);
				try
				{
					payeesTable.TableModel.Rows[0].Cells[1].Text = "0.0";
				}
				catch
				{
				}
//				totalRow = consumersTable.TableModel.Rows.Count;
//				while(totalRow!=1)
//					consumersTable.TableModel.Rows.RemoveAt(totalRow--);
				try
				{
					consumersTable.TableModel.Rows[0].Cells[1].Text = "0.0";
				}
				catch
				{
				}
				//consumersTable.TableModel.Rows.Clear();
				try
				{
					showTotalAmount();
				}
				catch
				{
				}
				addConsumerButton.Enabled = true;
				remConsumerButton.Enabled = true;
				addPayeeButton.Enabled = true;
				remPayeeButton.Enabled = true;
			}
			
		}

		private void amountBox_KeyUp(object sender, KeyEventArgs e)
		{
			double amount=0;
			if (e.KeyCode == Keys.Enter)
			{
				try
				{
					amount += Convert.ToDouble(amountBox.Text);
					int totalRow = consumersTable.TableModel.Rows.Count;
					consumersTable.TableModel.Rows[0].Cells[1].Text = amountBox.Text;
					payeesTable.TableModel.Rows[0].Cells[1].Text = amountBox.Text;
					showTotalAmount();
					
				}
				catch
				{
					MessageBox.Show("The format of the amount entered is incorrect.","Creating transaction",
						MessageBoxButtons.OK,MessageBoxIcon.Error);
				}
			}
		}

		private void amountBox_TextChanged(object sender, System.EventArgs e)
		{
			double amount=0;

				try
				{
					amount += Convert.ToDouble(amountBox.Text);
					int totalRow;
					if(consumersTable.TableModel != null)
					{
						totalRow = consumersTable.TableModel.Rows.Count;
						consumersTable.TableModel.Rows[0].Cells[1].Text = amountBox.Text;
						payeesTable.TableModel.Rows[0].Cells[1].Text = amountBox.Text;
						showTotalAmount();
					}
					
				}
				catch
				{
					MessageBox.Show("The format of the amount entered is incorrect.","Editing transaction",
						MessageBoxButtons.OK,MessageBoxIcon.Error);
				}	
		}

        /// <summary>
        /// Called whenever service is offline. Simply dispose the form, and forget everything.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        private void onServerDisconnected(object sender, MizEventArgs.ServiceDisconnectEventArgs ev)
        {
            this.Dispose();
        }
	}
}
